<template>
  <view class="goods-buy-modal" v-if="visible" @click="closeModal">
    <view class="modal-content" @click.stop>
      <!-- 商品信息头部 -->
      <view class="goods-header">
        <view class="goods-image">
          <image class="product-image" :src="goodsInfo.image || '/static/Images/goods/default-product.png'" mode="aspectFill"></image>
        </view>
        <view class="goods-info">
          <text class="goods-title">{{ goodsInfo.title || '【账号充值】芒果TV会员7天' }}</text>
          <view class="price-info">
            <text class="current-price">¥{{ totalAmount }}</text>
            <text class="stock-text">库存：{{ goodsInfo.stock }}</text>
          </view>
        </view>
        <view class="close-btn" @click="closeModal">
          <text class="close-icon">×</text>
        </view>
      </view>
      
      <!-- 商品信息 -->
      <view class="product-info">
        <!-- 非卡密商品显示充值账号 -->
        <view v-if="goodsInfo.type !== 2" class="info-item">
          <text class="info-label">* 充值账号：</text>
          <text class="info-value">{{ accountNumber || '19851642175' }}</text>
        </view>
        
        <!-- 卡密分配详情 -->
        <view v-if="cardKeyOrderParams && cardKeyOrderParams.allocationSummary" class="allocation-details">
          <text class="allocation-title">卡密分配详情：</text>
          <view class="allocation-list">
            <view v-for="(item, index) in cardKeyOrderParams.allocationSummary.priceBreakdown" :key="index" class="allocation-item">
              <text class="allocation-text">单价 ¥{{ item.price }} × {{ item.quantity }}张 = ¥{{ item.subtotal.toFixed(2) }}</text>
            </view>
          </view>
          <view class="allocation-summary">
            <text class="summary-text">总计：{{ cardKeyOrderParams.allocationSummary.totalQuantity }}张，¥{{ cardKeyOrderParams.allocationSummary.totalPrice.toFixed(2) }}</text>
          </view>
        </view>
      </view>

      <!-- 支付方式选择 -->
      <view class="payment-section">
        <text class="payment-title">请选择您的支付方式</text>
        
        <!-- 支付宝支付，仅 H5 且非微信内置浏览器显示 -->
        <!-- #ifdef H5 -->
        <view v-if="!isWeChatH5" class="payment-option" :class="{ active: selectedPayment === 'alipay' }" @click="selectPayment('alipay')">
          <view class="payment-left">
            <image class="payment-icon" :src="selectedPayment === 'alipay' ? '/static/Images/goods/Zhifubaohong.png' : '/static/Images/goods/Zhifubaohei.png'" mode="aspectFit"></image>
            <text class="payment-text">支付宝支付</text>
          </view>
          <view class="radio-btn" :class="{ active: selectedPayment === 'alipay' }">
            <view class="radio-inner" v-if="selectedPayment === 'alipay'"></view>
          </view>
        </view>
        <!-- #endif -->

        <!-- 微信支付 -->
        <view class="payment-option" :class="{ active: selectedPayment === 'wechat' }" @click="selectPayment('wechat')">
          <view class="payment-left">
            <image class="payment-icon" :src="selectedPayment === 'wechat' ? '/static/Images/goods/Weixinhong.png' : '/static/Images/goods/Weixinhei.png'" mode="aspectFit"></image>
            <text class="payment-text">微信支付</text>
          </view>
          <view class="radio-btn" :class="{ active: selectedPayment === 'wechat' }">
            <view class="radio-inner" v-if="selectedPayment === 'wechat'"></view>
          </view>
        </view>

        <!-- 余额支付 -->
        <view class="payment-option" :class="{ active: selectedPayment === 'balance' }" @click="selectPayment('balance')">
          <view class="payment-left">
            <image class="payment-icon" :src="selectedPayment === 'balance' ? '/static/Images/goods/Yuehong.png' : '/static/Images/goods/Yueehei.png'" mode="aspectFit"></image>
            <text class="payment-text">余额支付</text>
          </view>
          <view class="radio-btn" :class="{ active: selectedPayment === 'balance' }">
            <view class="radio-inner" v-if="selectedPayment === 'balance'"></view>
          </view>
        </view>
      </view>

      <!-- 立即支付按钮 -->
      <view class="pay-button" @click="handlePay">
        <text class="pay-text">立即支付 ¥{{ totalAmount }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { goodsApi } from '@/utils/api'
import { userStorage } from '@/utils/storage'

export default {
  name: 'GoodsBuy',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    goodsInfo: {
      type: Object,
      default: () => ({
        title: '',
        price: '',
        stock: '',
        image: ''
      })
    },
    accountNumber: {
      type: String,
      default: '19851642175'
    },
    orderId: {
      type: [String, Number],
      required: false,
      default: ''
    },
    quantity: {
      type: Number,
      default: 1
    },
    accountCount: {
      type: Number,
      default: 1
    },
    cardKeyOrderParams: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      selectedPayment: 'wechat', // 默认选择微信支付
      isWeChatH5: false // H5 环境下是否为微信内置浏览器
    }
  },
  computed: {
    totalAmount() {
      // 如果是卡密商品且有智能分配结果，使用分配结果的总价
      if (this.cardKeyOrderParams && this.cardKeyOrderParams.allocationSummary) {
        const totalPrice = this.cardKeyOrderParams.allocationSummary.totalPrice || 0;
        console.log('支付组件计算总价（卡密智能分配）:');
        console.log('- 分配结果总价:', totalPrice);
        console.log('- 分配详情:', this.cardKeyOrderParams.allocationSummary.priceBreakdown);
        return totalPrice.toFixed(2);
      }
      
      // 普通商品的价格计算
      const price = parseFloat(this.goodsInfo.price) || 0
      const qty = this.quantity || 1
      const accountCount = this.accountCount || 1
      
      console.log('支付组件计算总价（普通商品）:');
      console.log('- 单价:', price);
      console.log('- 数量:', qty);
      console.log('- 账号数量:', accountCount);
      console.log('- 计算结果:', (price * qty * accountCount).toFixed(2));
      
      // 多账号模式：单价 × 数量 × 账号数量
      return (price * qty * accountCount).toFixed(2)
    }
  },
  mounted() {
    // #ifdef H5
    try {
      this.isWeChatH5 = typeof navigator !== 'undefined' && /MicroMessenger/i.test(navigator.userAgent)
    } catch (e) {
      this.isWeChatH5 = false
    }
    // #endif
  },
  methods: {
    closeModal() {
      this.$emit('close')
    },
    selectPayment(type) {
      this.selectedPayment = type
    },
    async handlePay() {
      console.log('支付按钮被点击')
      
      // 获取token
      const token = userStorage.getToken()
      
      // 映射支付方式到type值
      const paymentTypeMap = {
        'balance': 0,  // 余额支付
        'wechat': 1,   // 微信支付
        'alipay': 2    // 支付宝支付
      }
      
      const paymentType = paymentTypeMap[this.selectedPayment]
      
      console.log('支付参数:', {
        token: token,
        orderId: this.orderId,
        paymentType: paymentType
      })
      
      try {
        uni.showLoading({
          // title: '支付中...'
        })
        
        // 构建支付参数
        const payParams = {
          token: token,
          id: this.orderId,
          type: paymentType,
          amount: this.totalAmount
        }
        
        // 微信支付时添加pay_type字段
        if (this.selectedPayment === 'wechat') {
          // #ifdef MP-WEIXIN
          payParams.pay_type = 1  // 小程序
          // #endif
          
          // #ifdef H5
          payParams.pay_type = 2  // H5和微信浏览器
          // #endif
        }
        
        // 调用支付接口
        const response = await goodsApi.userOrderPay(payParams)
        
        console.log('支付接口响应:', response)
        console.log('响应中的msg字段:', response.msg)
        console.log('响应数据类型:', typeof response)
        console.log('响应完整结构:', JSON.stringify(response, null, 2))
        
        uni.hideLoading()
        
        // 处理支付响应
        if (response.code === 1) {
          // 支付宝支付
          if (this.selectedPayment === 'alipay') {
            this.handleAlipayPayment(response.data)
          }
          // 微信支付
          else if (this.selectedPayment === 'wechat') {
            this.handleWechatPayment(response.data)
          }
          // 余额支付
          else if (this.selectedPayment === 'balance') {
            this.handleBalancePayment(response)
          }
        } else {
          uni.showToast({
            title: response.msg || '支付失败，请重试',
            icon: 'none'
          })
        }
        
      } catch (error) {
        uni.hideLoading()
        console.error('支付失败:', error)
        
        uni.showToast({
          title: error.message || '支付失败，请重试',
          icon: 'none'
        })
      }
    },
    
    // 处理支付宝支付
    handleAlipayPayment(formHtml) {
      try {
        // #ifdef H5
        // H5环境下直接将表单插入页面并提交
        const tempDiv = document.createElement('div')
        tempDiv.innerHTML = formHtml
        document.body.appendChild(tempDiv)
        
        // 查找并提交表单
        const form = tempDiv.querySelector('form')
        if (form) {
          form.submit()
        }
        
        // 清理临时元素
        setTimeout(() => {
          document.body.removeChild(tempDiv)
        }, 1000)
        // #endif
        
        // #ifdef MP-WEIXIN
        // 小程序环境下提示用户
        uni.showToast({
          title: '请在浏览器中完成支付',
          icon: 'none'
        })
        // #endif
        
        // 触发支付事件
        this.$emit('pay', {
          paymentType: this.selectedPayment,
          amount: this.totalAmount,
          goodsInfo: this.goodsInfo,
          formHtml: formHtml
        })
        
      } catch (error) {
        console.error('支付宝支付处理失败:', error)
        uni.showToast({
          title: '支付处理失败，请重试',
          icon: 'none'
        })
      }
    },
    
    // 处理微信支付
    handleWechatPayment(paymentData) {
      try {
        // 触发微信支付事件，由父组件处理具体的微信支付逻辑
        this.$emit('pay', {
          paymentType: this.selectedPayment,
          amount: this.totalAmount,
          goodsInfo: this.goodsInfo,
          paymentData: paymentData
        })
      } catch (error) {
        console.error('微信支付处理失败:', error)
        uni.showToast({
          title: '支付处理失败，请重试',
          icon: 'none'
        })
      }
    },
    
    // 处理余额支付
    handleBalancePayment(response) {
      try {
        uni.showToast({
          title: '余额支付成功',
          icon: 'success'
        })
        
        // 触发支付成功事件
        this.$emit('pay', {
          paymentType: this.selectedPayment,
          amount: this.totalAmount,
          goodsInfo: this.goodsInfo,
          response: response
        })
        
        // 关闭弹窗
        this.closeModal()
      } catch (error) {
        console.error('余额支付处理失败:', error)
        uni.showToast({
          title: '支付处理失败，请重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.goods-buy-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: flex-end;
  z-index: 1000;
}

.modal-content {
  width: 100%;
  background-color: #ffffff;
  border-radius: 20px 20px 0 0;
  padding: 20px;
  max-height: 80vh;
  overflow-y: auto;
}

/* 商品信息头部 */
.goods-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 20px;
  position: relative;
}

.goods-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.product-image {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
}

.goods-info {
  flex: 1;
  padding-right: 30px;
}

.goods-title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
  line-height: 1.4;
  margin-bottom: 8px;
}

.price-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.current-price {
  font-size: 20px;
  font-weight: 600;
  color: #ff4757;
}

.stock-text {
  font-size: 14px;
  color: #999999;
}

.close-btn {
  position: absolute;
  top: 0;
  right: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-icon {
  font-size: 20px;
  color: #999999;
  font-weight: bold;
}

/* 商品信息 */
.product-info {
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  font-size: 14px;
  color: #333333;
}

.info-value {
  font-size: 14px;
  color: #666666;
}

/* 卡密分配详情 */
.allocation-details {
  margin-top: 16px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.allocation-title {
  font-size: 14px;
  font-weight: 500;
  color: #333333;
  margin-bottom: 8px;
}

.allocation-list {
  margin-bottom: 8px;
}

.allocation-item {
  margin-bottom: 4px;
}

.allocation-text {
  font-size: 13px;
  color: #666666;
  line-height: 1.4;
}

.allocation-summary {
  padding-top: 8px;
  border-top: 1px solid #e0e0e0;
}

.summary-text {
  font-size: 14px;
  font-weight: 500;
  color: #ff4757;
}

/* 支付方式 */
.payment-section {
  margin-bottom: 24px;
}

.payment-title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
  margin-bottom: 16px;
}

.payment-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-bottom: 12px;
  transition: all 0.3s ease;
}

.payment-option.active {
  border-color: #ff4757;
  background-color: #fff5f5;
}

.payment-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.payment-icon {
  width: 24px;
  height: 24px;
}

.payment-text {
  font-size: 14px;
  color: #333333;
}

.radio-btn {
  width: 20px;
  height: 20px;
  border: 2px solid #e0e0e0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.radio-btn.active {
  border-color: #ff4757;
}

.radio-inner {
  width: 10px;
  height: 10px;
  background-color: #ff4757;
  border-radius: 50%;
}

/* 支付按钮 */
.pay-button {
  width: 100%;
  height: 48px;
  background-color: #ff4757;
  border-radius: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}

.pay-text {
  font-size: 16px;
  font-weight: 500;
  color: #ffffff;
}
</style>